<template>
	<view class="content">
		<view>
			打印机的 IP 地址: <input type="text" v-model="ip" />
		</view>
		<view>
			打印机的 TCP 端口号: <input type="text" v-model="port" />
		</view>
		<view>
			连接超时时间(ms): <input type="text" v-model="timeout" />
		</view>
		<view class="printer-controls">
			<button class="btn" @click="connectPrinter">连接打印机</button>
			<button class="btn" @click="printTestLabel">打印测试标签</button>
			<button class="btn" @click="disconnectPrinter">断开连接</button>
		</view>

		<view class="status">
			<text>状态: {{ status }}</text>
		</view>
	</view>
</template>

<script>
	import printUtil from '@/utils/printUtil.js';

	export default {
		data() {
			return {
				status: '未连接',
				isConnected: false,
				ip: '199.9.10.220',
				port: 9100,
				timeout: 3000
			};
		},
		methods: {
			async connectPrinter() {
				try {
					this.status = '正在连接...';
					// 替换为您的打印机IP地址
					await printUtil.connectNetworkPrinter(this.ip, this.port, this.timeout);
					this.status = '已连接';
					this.isConnected = true;
					uni.showToast({
						title: '打印机连接成功',
						icon: 'success'
					});
				} catch (error) {
					this.status = '连接失败';
					uni.showToast({
						title: '连接失败: ' + error,
						icon: 'none'
					});
				}
			},

			async printTestLabel() {
				if (!this.isConnected) {
					uni.showToast({
						title: '请先连接打印机',
						icon: 'none'
					});
					return;
				}

				try {
					this.status = '正在打印...';

					// 打印文本
					await printUtil.printText(50, 30, "测试标签");
					await printUtil.printText(50, 60, "产品: 测试产品");
					await printUtil.printText(50, 90, "日期: " + new Date().toLocaleDateString());

					// 打印标签
					await printUtil.printLabel(1, 1);

					this.status = '打印完成';
					uni.showToast({
						title: '打印成功',
						icon: 'success'
					});
				} catch (error) {
					this.status = '打印失败';
					uni.showToast({
						title: '打印失败: ' + error,
						icon: 'none'
					});
				}
			},

			async disconnectPrinter() {
				try {
					await printUtil.disconnectPrinter();
					this.status = '已断开';
					this.isConnected = false;
					uni.showToast({
						title: '已断开打印机连接',
						icon: 'success'
					});
				} catch (error) {
					uni.showToast({
						title: '断开连接失败: ' + error,
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style>
	.content {
		padding: 20px;
	}

	.printer-controls {
		margin-bottom: 20px;
	}

	.btn {
		margin-bottom: 10px;
		background-color: #007AFF;
		color: white;
	}

	.status {
		margin-top: 20px;
		text-align: center;
		font-size: 16px;
	}
</style>